package com.cuitrip.business.share.ui;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.cuitrip.app.util.FontManager;
import com.cuitrip.business.share.ShareChannelBuilder;
import com.cuitrip.business.share.model.ServiceShareObject;
import com.cuitrip.business.share.model.Share;
import com.cuitrip.business.share.model.ShareParamBuilder;
import com.cuitrip.component.recyclerview.ItemClickSupport;
import com.cuitrip.service.R;
import com.cuitrip.util.DialogUtil;
import com.lab.component.common.BaseDialogFragment;
import com.lab.rtenvironment.AppCoreRuntime;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 分享框
 * Created by ak on 2014/12/24.
 */
public class ShareDialogFragment extends BaseDialogFragment {


    public static final String DATA_KEY = "data";
    public static final String IMAGE_KEY = "image";
    /**
     * 分享类型：邀请好友，分享服务
     */
    public static final  String SHARE_TYPE  = "share_type";

    @Bind(R.id.id_recyclerview)
    RecyclerView mRecycleView;

    @Bind(R.id.background)
    ImageView mImageView;

    private Bitmap bitmap;

    private ShareAdapter mShareAdapter;

    private ServiceShareObject shareObject;

    private int shareType;

    private List<ShareChannelBuilder.TripShareChannel> shareList;

    public static ShareDialogFragment newInstance(int shareType, Bitmap bitmap) {
        return newInstance(null, shareType, bitmap);
    }

    public static ShareDialogFragment newInstance(ServiceShareObject shareObject, int shareType, Bitmap bitmap) {
        ShareDialogFragment l = new ShareDialogFragment();
        Bundle b = new Bundle();
        b.putSerializable(DATA_KEY, shareObject);
        b.putParcelable(IMAGE_KEY, bitmap);
        b.putInt(SHARE_TYPE, shareType);
        l.setArguments(b);
        return l;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.contextMenu);
        Bundle arguments = getArguments();
        if (arguments != null){
            if (arguments.containsKey(DATA_KEY)){
                shareObject = (ServiceShareObject) arguments.getSerializable(DATA_KEY);
            }
            bitmap = arguments.getParcelable(IMAGE_KEY);
            shareType = arguments.getInt(SHARE_TYPE);
        }else{
            hideDialogFragment(this);
        }
        ShareSDK.initSDK(AppCoreRuntime.context);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.share_panel, container, false);
        FontManager.resetViewFont(v, true);
        ButterKnife.bind(this, v);
        shareList = ShareChannelBuilder.inflateInviteSimpleShareList();
        mShareAdapter = new ShareAdapter();
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.setAdapter(mShareAdapter);
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        mShareAdapter.setShareList(shareList);
        ItemClickSupport.addTo(mRecycleView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                ShareChannelBuilder.TripShareChannel shareChannel = mShareAdapter.getShareList().get(position);
                Share share = ShareChannelBuilder.getShareObject(shareType, shareChannel, shareObject);
                if (Share.COPY_ACTION.equals(share.media)){
                    String url = share.detailUrl;
                    ClipboardManager clipboardManager = (ClipboardManager)getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData data = ClipData.newPlainText("text", url);
                    clipboardManager.setPrimaryClip(data);
                    Toast.makeText(getActivity(),R.string.share_copy_suc,Toast.LENGTH_SHORT).show();
                    hideDialogFragment(ShareDialogFragment.this);
                    return;
                }else if (Share.MORE_ACTION.equals(share.media)){
                    int lastPosition = shareList.size() - 1;
                    shareList.remove(lastPosition);
                    mShareAdapter.notifyItemRemoved(lastPosition);
                    int count = ShareChannelBuilder.addMoreInviteShareList(shareList);
                    mShareAdapter.notifyItemRangeInserted(lastPosition, count);
                    mRecycleView.smoothScrollToPosition(shareList.size() - 1);
                    return;
                }else if (Share.TITLE_ACTION.equals(share.media)){
                    return;
                }
                shareTo(share);
            }
        });
        mImageView.setImageBitmap(bitmap);
        return v;
    }

    public void shareTo(Share share){

        final OnekeyShare oks = new OnekeyShare();
        //不同平台的分享参数，请看文档
        //http://wiki.mob.com/Android_%E4%B8%8D%E5%90%8C%E5%B9%B3%E5%8F%B0%E5%88%86%E4%BA%AB%E5%86%85%E5%AE%B9%E7%9A%84%E8%AF%A6%E7%BB%86%E8%AF%B4%E6%98%8E

        oks.setTheme(OnekeyShareTheme.SKYBLUE);
        String text = share.content;
        oks.setTitle(share.title);
        oks.setText(text);
        if (!TextUtils.isEmpty(share.detailUrl)){
            oks.setUrl(share.detailUrl);
        }
        if (share.media != null) {
            oks.setPlatform(share.media);
            if (share.media.equals(QQ.NAME)){
                oks.setTitleUrl(share.detailUrl);
            }
            /**
             * 修复微信被登出缓存未清除
             */
            else if (share.media.equals(Wechat.NAME)){
                Wechat wechat = new Wechat(AppCoreRuntime.context);
                wechat.removeAccount(true);
            }
        }
        if(share.imgPath!=null){
            oks.setPlatform(share.media);
            if (share.media.equals(Facebook.NAME) && shareType == ShareChannelBuilder.TripShareChannel.TRIP_TYPE){
                oks.setImagePath(share.imgPath);
            }
        }

        if (!TextUtils.isEmpty(share.imgUrl)) {
            oks.setImageUrl(share.imgUrl);
        }
        hideDialogFragment(this);
        oks.show(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.close)
    void blankClick() {
        hideDialogFragment(this);
    }

}
